import React from 'react';
import { useDebounceFn, useSetState } from 'ahooks';
import * as echarts from 'echarts';
import emitter from '#/utils/events';
import { TRTooltip } from '@/components';
import { getPowerCharts } from './helper';

function Charts({ config = [], onGetData, signPoint, columnsText }) {
  let chartInstance = null;
  const [configs, setConfigs] = useSetState({});
  const chartRef = React.useRef(null);
  let __tooltip_ = React.useRef(null);
  const resizeHelper = useDebounceFn(
    () => {
      chartInstance =
        echarts.getInstanceByDom(chartRef?.current) || echarts.init(chartRef?.current);
      chartInstance?.resize();
    },
    { wait: 300 },
  );

  React.useEffect(() => {
    const configList = getPowerCharts(config, _tooltipFormatter);
    onGetData(columnsText, configList.series, signPoint);
    setConfigs(configList);
  }, [JSON.stringify(config), JSON.stringify(columnsText)]);

  React.useEffect(() => {
    renderChart();
  }, [configs]);

  React.useEffect(() => {
    mounted();
    return () => {
      destoryed();
    };
  }, []);

  function destoryed() {
    chartInstance?.dispose();
    window.removeEventListener('resize', resizeHelper.run);
    emitter.removeListener('onChangeMnue', resizeHelper.run);
  }

  function mounted() {
    window.addEventListener('resize', resizeHelper.run);
    emitter.addListener('onChangeMnue', resizeHelper.run);
  }

  function renderChart() {
    chartInstance = echarts.getInstanceByDom(chartRef?.current) || echarts.init(chartRef?.current);
    chartInstance?.setOption(configs, true);
    chartInstance.dispatchAction({
      type: 'showTip',
      seriesIndex: 0,
      dataIndex: 0,
    });
    chartInstance?.resize();
  }

  function _tooltipFormatter(params) {
    let array = [];
    let timer = '';
    params.forEach((item) => {
      timer = item.axisValue;
      const { color } = item;
      array.push({
        name: item.seriesName,
        value: item.value || item.value === 0 ? Number(item.value).toFixed(3) : '-',
        color,
      });
    });
    __tooltip_ && __tooltip_.current.show(timer, array, 'powerAndelectricId', 1);
  }

  return (
    <>
      <TRTooltip ref={__tooltip_} suffixText={'单位:MW'} />
      <div id="a" ref={chartRef} style={{ width: '100%', height: '580px' }} />
    </>
  );
}

export default Charts;
